<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>试题录入</span>
    </div>
    <el-form label-width="80px" :model="form" :rules="rules" ref="form">
      <!-- 学科 -->
      <el-form-item label="学科:" prop="userSubject">
        <el-select
          v-model="form.userSubject"
          placeholder="请选择"
          @change="hchangesub"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in form.subjects"
            :key="index"
          ></el-option>
          <!-- <el-option label="区域二" value="beijing"></el-option> -->
        </el-select>
      </el-form-item>
      <!-- 目录 -->
      <el-form-item label="目录:" prop="usercatalog">
        <el-select v-model="form.usercatalog" placeholder="请选择">
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in usercatalog"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 企业 -->
      <el-form-item label="企业:" prop="userCompanys">
        <el-select placeholder="请选择" v-model="form.userCompanys">
          <el-option
            :label="item.shortName"
            v-for="item in form.Companys"
            :key="item.id"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 城市 -->
      <el-form-item label="城市:" prop="userCitys">
        <el-select
          v-model="form.userCitys"
          placeholder="请选择"
          @change="hchangecity"
        >
          <el-option
            :label="item"
            :value="item"
            v-for="(item, index) in userCitys"
            :key="index"
          ></el-option> </el-select
        >&nbsp;
        <el-select v-model="form.userCitys2" placeholder="请选择">
          <el-option
            :label="item"
            :value="item"
            v-for="(item, index) in userCitys2"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 方向 -->
      <el-form-item label="方向:" prop="userDirection">
        <el-select v-model="form.userDirection" placeholder="请选择">
          <el-option
            :label="item"
            :value="item"
            v-for="(item, index) in form.direction"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 题型 -->
      <el-form-item label="题型:" prop="userType">
        <el-radio-group v-model="form.userType">
          <el-radio :label="1" value="1">单选</el-radio>
          <el-radio :label="2" value="2">多选</el-radio>
          <el-radio :label="3" value="3">简答</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 难度 -->
      <el-form-item label="难度:" prop="userdifficulty">
        <el-radio-group v-model="form.userdifficulty">
          <el-radio :label="1">简单</el-radio>
          <el-radio :label="2">一般</el-radio>
          <el-radio :label="3">困难</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 题干-->
      <el-form-item label="题干:" prop="userTag">
        <!-- 富文本 编辑器 -->
        <quill-editor class="editor"></quill-editor>
      </el-form-item>
      <!-- 选项-->
      <el-form-item label="选项:" v-if="form.userType !== 3">
        <!-- 单选框 , 输入框 , 上传 -->
        <el-radio-group
          v-model="form.userCheck"
          v-if="form.userType === 1"
          @change="hradioChange"
        >
          <div class="col" v-for="(item, index) in options" :key="index">
            <div class="row">
              <!--  选项部分 -->
              <!-- <el-checkbox :label="item.code" ></el-checkbox> -->
              <el-radio :label="item.code"></el-radio>
              <el-input v-model="item.title"></el-input>
              <el-upload
                action=""
                class="avatar-uploader"
                :http-request="hUpload"
                :show-file-list="false"
              >
                <img v-if="item.imageUrl" :src="item.imageUrl" class="avatar" />
                <i v-else class="avater-text">上传图片</i>
              </el-upload>
            </div>
          </div>
        </el-radio-group>
        <!-- 复选框 输入框 上传  -->
        <el-checkbox-group
          v-model="form.userCheckList"
          v-else-if="form.userType === 2"
          @change="hcheckboxChange"
        >
          <div class="col" v-for="(item, index) in options" :key="index">
            <div class="row">
              <!-- 选项部分 -->
              <el-checkbox
                :label="item.code"
                v-if="form.userType === 2"
              ></el-checkbox>
              <!-- <el-radio :label="item.code"  v-else-if="form.userType === '单选'"></el-radio> -->
              <el-input
                v-model="item.title"
                style="width: 300px; margin-left: 30px"
              ></el-input>
              <el-upload
                action=""
                class="avatar-uploader"
                :http-request="hUpload"
                :show-file-list="false"
              >
                <img v-if="item.imageUrl" :src="item.imageUrl" class="avatar" />
                <i v-else class="avater-text">上传图片</i>
              </el-upload>
            </div>
          </div>
        </el-checkbox-group>
        <!-- 添加按钮部分 -->
        <div class="row">
          <el-button
            type="danger"
            :disabled="form.userType === 1 ? true : false"
            @click="haddoption"
            >+增加选项与答案</el-button
          >
        </div>
      </el-form-item>
      <!-- 解析视频 -->
      <el-form-item label="解析视频:">
        <el-input v-model="form.videoURL"></el-input>
      </el-form-item>
      <!-- 答案解析-->
      <el-form-item
        label="答案解析"
        prop="userAnswer"
        v-model="form.userAnswer"
      >
        <!-- 富文本 编辑器 -->
        <quill-editor class="editor"> </quill-editor>
      </el-form-item>
      <br />
      <!-- 题目备注 -->
      <el-form-item label="题目备注:">
        <el-input type="textarea" v-model="form.remarks"></el-input>
      </el-form-item>
      <!-- 试题标签 -->
      <el-form-item label="试题标签" class="userTag" prop="userTag">
        <!--<el-select-->
        <!--  v-if="this.$route.query.id"-->
        <!--  v-model="form.userTag"-->
        <!--  placeholder="请选择试题标签"-->
        <!--  multiple-->
        <!--  filterable-->
        <!--  allow-create-->
        <!--  default-first-option-->
        <!--&gt;-->
        <!--</el-select>-->
        <el-select
          v-model="form.userTag"
          placeholder="请选择试题标签"
          multiple
          filterable
          allow-create
          default-first-option
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="(item, index) in userTag"
            :key="index"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 提交 修改 按钮 -->
      <el-form-item>
        <!-- 试题修改 修改按钮 -->
        <el-button type="success" v-if="this.$route.query.id" @click="hUpdate"
          >确认修改</el-button
        >
        <!-- 试题录入 提交按钮 -->
        <el-button type="primary" @click="hSubmit" v-else>确认提交</el-button>
      </el-form-item>
    </el-form>
    <!-- 表单 部分 end -->
  </el-card>
</template>

<script>
// 导入富文本编辑组件
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 导入企业
import { getCompanys } from '@/api/hmmm/companys.js'
// 导入城市接口 // 获取二级区
import { citys, provinces } from '@/api/hmmm/citys.js'
// 导入 方向接口
import { direction } from '@/api/hmmm/constants.js'
// 导入学科目录
import { getSubject } from '@/api/hmmm/subjects'
// 获取目录
import { list } from '@/api/hmmm/directorys'
// 获取标签
import { getTags } from '@/api/hmmm/tags'

export default {
  name: 'que-new',
  // 注册组件
  components: {
    quillEditor
  },
  data () {
    return {
      form: {
        subjects: [],
        Companys: [],
        // citys: null,
        // citys2: null,
        direction: [],
        tags: [],
        // 备注
        remarks: null,
        // 富文本编辑器1 --题干
        content1: '',
        // 学科列表 -- 双向绑定
        userSubject: null,
        // 目录列表 -- 双向绑定
        usercatalog: '',
        // 企业管理 -- 双向绑定
        userCompanys: '',
        // 城市渲染 -- 双向绑定
        userCitys: '',
        userCitys2: '',
        // 方向渲染 -- 双向绑定
        userDirection: '',
        // 题型选择 -- 双向绑定
        userType: 1,
        // 题型难度 -- 双向绑定
        userdifficulty: 1,
        // 试题标签 -- 双向绑定
        userTag: [],
        // 题型选择 radio  --- 双向绑定
        userCheck: '',
        // 答案解析 -- 双向绑定
        userAnswer: '',
        // 复选框的选择项  -- 双向绑定
        userCheckList: [],
        // 用户的选择项数据 --双向绑定
        userOptions: [],
        // 视频解析项 --双向绑定
        videoURL: null
      },
      userCitys: provinces(),
      userCitys2: [],
      usercatalog: [],
      userTag: [],
      rules: {
        userSubject: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        usercatalog: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        userCompanys: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        userCitys: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        userDirection: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        userType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        userdifficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        userTag: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        userAnswer: [{ message: '请输入答案解析', trigger: 'blur' }]
      },
      options: [
        {
          code: 'A',
          isRight: 'false',
          title: '',
          imageUrl: ''
        },
        {
          isRight: 'false',
          title: '',
          code: 'B',
          imageUrl: ''
        },
        {
          isRight: 'false',
          code: 'C',
          title: '',
          imageUrl: ''
        },
        {
          isRight: 'false',
          code: 'D',
          title: '',
          imageUrl: ''
        }
      ],
      content: null
    }
  },
  // 监听列表表单的切换
  watch: {
    // 监听 城市省份的变化
    'form.userCitys': {
      async handler (newValue) {
        const res = await provinces(newValue)
        this.citys2 = res
      },
      immediate: true
    },
    // 监听 学科列表的变化
    'form.userSubject': {
      async handler (newValue) {
      },
      immediate: true
    },
    // 监听路由的变化
    $route (val) {
      console.log(val.query.id)
      if (val.query.id) {
        this.loadDetail()
      } else {
        this.$refs.form.resetFields()
      }
    }
  },
  created () {
    this.loadSubject()
    this.loadCompany()
    // this.loadCitys()
    this.loadDirection()
    // this.loadTags()
    if (this.$route.query.id) {
      this.loadDetail()
    }
  },
  methods: {
    // 当城市更换的时候将后面的城区清空
    hchangecity (val) {
      // this.form.userCitys2 = ''
      this.userCitys2 = citys(val)
      console.log(this.userCitys2)
    },
    // 当学科改变的时候
    async hchangesub (id) {
      // 1. 根据学科id获取目录和标签
      // this.form.userTag = ''
      // this.form.usercatalog = ''
      const { data } = await list({ subjectID: id })
      this.usercatalog = data
      const res = await getTags({ subjectID: id })
      this.userTag = res.data
      console.log(this.userTag)
    },
    // 题库试题的修改提交
    async LoadUpdate () {
      try {
        // const res = await update()
        // console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    // 获取请求 学科列表
    async loadSubject () {
      try {
        const res = await getSubject()
        // 1. 请求成功 打印结果
        // console.log(res.data)
        // 2.将请求的结果赋值给数据项
        console.log(res)
        this.form.subjects = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取请求 企业列表
    async loadCompany () {
      try {
        const res = await getCompanys()
        console.log(res)
        this.form.Companys = res.data.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取请求 所有的城市
    // async loadCitys () {
    //   try {
    //     const res = await provinces()
    //     // console.log(res)
    //     this.form.citys = res
    //   } catch (err) {
    //     console.log(err)
    //   }
    // },
    // 获取请求 方向
    loadDirection () {
      try {
        const res = direction
        // console.log(res)
        this.form.direction = res
      } catch (err) {
        console.log(err)
      }
    },
    // 图片上传成功的事件
    async hUpload (fileObj) {
      const fd = new FormData()
      // 将选中的图片添加到fd对象中
      fd.append('photo', fileObj.file)
      // 发送请求
    },
    // 点击选项添加按钮 进行选项的添加
    haddoption () {
      // console.log(String.fromCharCode(this.options[this.options.length - 1].code.charCodeAt(0) + 1))
      // 实现添加功能
      this.options.push({
        isRight: 'false',
        code: String.fromCharCode(this.options[this.options.length - 1].code.charCodeAt(0) + 1),
        title: '',
        imageUrl: ''
      })
    },
    // 单选框表单组发生变化发生的事件
    hradioChange (val) {
      // 1. 获取点击的 code 的值
      this.form.userCheck = val
      // 2. 更改option数据项
      this.options.map((item, index) => {
        if (item.code === val) {
          // 更改当前项的 isRight的值
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 将 isRight为true 的数组 进行筛选出来
      // 将数组赋值给数据项
      this.form.userOptions = this.options.filter(item => {
        return item.isRight === true
      })
    },
    //  多选框发生变化的时候 发生的事件
    hcheckboxChange (val) {
      this.form.userCheckList = val
      console.log(val)
      this.options.map((item, index) => {
        if (val.includes(item.code)) {
          // 更改当前的 isRight 值
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 将符合条件的数组筛选出来 赋值给数据线
      this.form.userOptions = this.options.filter(item => {
        return item.isRight === true
      })
    },
    // 数据验证以及表单数据获取
    doSave () {
      //  1. 进行表单验证
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 2.表单验证通过 获取表单数据
          const data = {
            subjectID: this.form.userSubject,
            catalogID: this.form.usercatalog,
            enterpriseID: this.form.userCompanys,
            city: this.form.userCitys,
            province: this.form.userCitys2,
            direction: this.form.userDirection,
            questionType: '' + this.form.userType,
            answer: this.form.userAnswer,
            difficulty: '' + this.form.userdifficulty,
            question: this.form.content1,
            options: this.form.userOptions,
            tags: toString(this.form.userTag),
            id: Number(this.$route.query.id),
            videoURL: this.form.videoURL === null ? '1' : this.form.videoURL,
            remarks: this.form.remarks === null ? '1' : this.form.videoURL
          }
          console.log('11111', data)
          // 3. 发送请求 提交数据
          // const res = await add(data)
          // console.log(res)
          // 4.请求成功 提示用户
          this.$message.success('试题录入成功')
          // 5. 请求成功 进行页面跳转
          this.$router.push('/questions/list')
        } else {
          this.$message.error('失败了')
        }
      })
    },
    // 点击提交 -- 实现试题录入
    hSubmit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.doSave()
        }
      })
    },
    // 点击 修改按钮 -- 实现试题修改
    hUpdate () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.doUpdate()
        }
      })
    },
    // 进行 修改 请求发送
    async doUpdate () {
      // 获取请求参数
      console.log(1)
      if (this.form.videoURL === null) {
        console.log(1)
      }
      // const res = await update(data)
      // console.log(res)
      // 1. 修改成功 提示用户修改试题成功
      this.$message.success('试题修改成功')
      // 2.清空表单内容
      this.$refs.form.resetFields()
      // 3.跳转到基础题库
      this.$router.push('/questions/list')
    }
  }
}
</script>

<style scoped lang='scss'>
.box-card {
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  margin: 20px;
}
.ql-editor {
  height: 200px;
}
.option_item {
  padding-bottom: 20px;
}
/* // 单选按钮 */
.el-radio-group .col {
  display: flex;
  flex-direction: column;
}

.el-radio,
.el-checkbox {
  margin-bottom: 30px;
  margin-right: 30px;
}
/* // 多选按钮 */
.el-checkbox-grop .col {
  display: flex;
  flex-direction: column;
}
.el-radio,
.el-checkbox {
  margin-bottom: 30px;
  margin-right: 30px;
}

.el-input {
  width: 300px;
}
/* // 上传图片 */
.avatar-uploader .el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
.avatar-uploader {
  text-align: center;
  margin-left: 10px;
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avater-text {
  font-size: 14px;
  color: #8c939d;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.editor {
  height: 200px;
  margin-bottom: 55px;
}
</style>
